/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package co.edu.distribuidos.tiempo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

/**
 *
 * @author alvar-go@uniandes.edu.co
 */
public final class AdministradorTiempo {

    private final static String SERVIDOR_NTP = "south-america.pool.ntp.org";

    public static Date darTiempo()throws Exception{
        try {
            // Send request
            DatagramSocket socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName(SERVIDOR_NTP);
            byte[] buf = new MensajeNTP().toByteArray();
            DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 123);

            // Set the transmit timestamp *just* before sending the packet
            // ToDo: Does this actually improve performance or not?
            MensajeNTP.encodeTimestamp(packet.getData(), 40,(System.currentTimeMillis()/1000.0) + 2208988800.0);

            socket.send(packet);

            // Get response
            packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);

            // Process response
            MensajeNTP msg = new MensajeNTP(packet.getData());
            return msg.darRecieveTimestamp();

        } catch (Exception e) {
            throw new Exception("No se pudo recuperar el tiempo UTC. " + e.getMessage());
        }
    }
}
